package com.guigu.tms.dispatch.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.guigu.tms.commons.aggregation.entity.*;
import com.guigu.tms.commons.aggregation.feign.*;
import com.guigu.tms.commons.dispatch.entity.CacheLineDetail;
import com.guigu.tms.commons.dispatch.entity.OrderClassify;
import com.guigu.tms.commons.dispatch.entity.OrderClassifyAttach;
import com.guigu.tms.commons.order.entity.Order;
import com.guigu.tms.commons.order.feign.OrderFeignClient;
import com.guigu.tms.dispatch.dto.OrderLineSimpleDTO;
import com.guigu.tms.dispatch.dto.OrderLineTripsTruckDriverDTO;
import com.guigu.tms.dispatch.service.IBusinessOperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BusinessOperationServiceImpl implements IBusinessOperationService {

    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private TransportOrderFeignClient transportOrderFeignClient;
    @Autowired
    private TaskTransportFeignClient taskTransportFeignClient;
    @Autowired
    private TransportTripsFeignClient transportTripsFeignClient;
    @Autowired
    private TransportLineFeignClient transportLineFeignClient;
    @Autowired
    private DriverJobFeignClient driverJobFeignClient;

    @Override
    public Map<String, TaskTransport> createTransportOrderTask(List<OrderLineSimpleDTO> orderLineSimpleDTOS) {
        HashMap<String, TaskTransport>  taskTransportMap= new HashMap<>();
        orderLineSimpleDTOS.forEach(item->{
            CacheLineDetail cacheLineDetail= item.getCacheLineDetail();
            List<OrderClassify> orderClassifies = item.getOrderClassifys();

            //用于存放运单编号
            List<String> transportOrderIds = new ArrayList<>();

            orderClassifies.forEach(item1->{
                //如果是新订单更新订单信息
                if(item1.isNew()){
                    item1.getOrders().forEach(item2->{
                        //根据订单编号修改订单状态为待发车
                        Order order = new Order();
                        order.setId(item2.getId());
                        order.setStatus(4);
                        //远程调用订单服务修改订单状态
                        orderFeignClient.updateOrderInfo(order);
                    });

                    //  查询运单信息构建运单集合
                    List<String> orderIds = item1.getOrders().stream().map(item3 -> item3.getId().toString()).collect(Collectors.toList());
                     //远程调用work服务查询运单集合
                    List<TransportOrder> transportOrders=transportOrderFeignClient.getTransportOrderByOrderIds(orderIds);

                    transportOrderIds.addAll(transportOrders.stream().map(a->a.getId()).collect(Collectors.toList()));
                }
            });

            //创建运输任务
            TaskTransport taskTransport = new TaskTransport();
            taskTransport.setId(IdWorker.getIdStr());
            taskTransport.setStartAgencyId(cacheLineDetail.getStartAgencyId());
            taskTransport.setEndAgencyId(cacheLineDetail.getEndAgencyId());
            taskTransport.setStatus(1);
            taskTransport.setAssignedStatus(1);
            taskTransport.setLoadingStatus(1);
            taskTransport.setTransportOrderIds(transportOrderIds);

            //保存运输任务
            taskTransportFeignClient.createTaskTransport(taskTransport);
            //线路关联运输任务
            taskTransportMap.put(cacheLineDetail.getId(),taskTransport);
        });
        return taskTransportMap;
    }

    @Override
    public void updateTransportTask(List<OrderLineTripsTruckDriverDTO> orderLineTripsTruckDrivers, Map<String, TaskTransport> transportTaskMap) {
        orderLineTripsTruckDrivers.forEach(orderLineTripsTruckDriver ->{
            String transportLineId=orderLineTripsTruckDriver.getTransportLineId();
            TransportTripsTruckDriver tripsTruckDriver=orderLineTripsTruckDriver.getTripsTruckDriver();
            //查询车次信息
            TransportTrips transportTrips = transportTripsFeignClient.getTransportTripsById(tripsTruckDriver.getTransportTripsId());

            //计算计划发车时间
            String[] departureDate=transportTrips.getDepartureTime().split(":");
            LocalDateTime planDepartureDate=LocalDateTime.now().withHour(Integer.parseInt(departureDate[0])).withMinute(Integer.parseInt(departureDate[0])).withSecond(00);

            //计算预计到达时间
            TransportLine transportLine=transportLineFeignClient.getTransportLineById(transportLineId);
            LocalDateTime planArrivalTime=planDepartureDate.plusMinutes(transportLine.getEstimatedTime().longValue());

            //运输任务
            TaskTransport taskTransport=transportTaskMap.get(transportLineId);

            //构建司机运输作业
            DriverJob driverJob=new DriverJob();
            driverJob.setId(IdWorker.getIdStr());
            driverJob.setDriverId(tripsTruckDriver.getUserId());
            driverJob.setTaskTransportId(taskTransport.getId());
            driverJob.setStartAgencyId(taskTransport.getStartAgencyId());
            driverJob.setEndAgencyId(taskTransport.getEndAgencyId());
            driverJob.setPlanDepartureTime(planDepartureDate);
            driverJob.setPlanArrivalTime(planArrivalTime);
            driverJob.setStatus(1);
            //保存司机运输作业
            driverJobFeignClient.createDriverJob(driverJob);
            //更新运输任务
            taskTransport.setTransportTripsId(tripsTruckDriver.getTransportTripsId());
            taskTransport.setTruckId(tripsTruckDriver.getTruckId());
            taskTransport.setAssignedStatus(2);
            taskTransport.setPlanDepartureTime(planDepartureDate);
            taskTransport.setPlanArrivalTime(planArrivalTime);
            taskTransport.setPlanPickUpGoodsTime(planDepartureDate);
            taskTransport.setPlanDeliveryTime(planArrivalTime);
            //保存更改
            taskTransportFeignClient.updateTaskTransport(taskTransport);
            //删除已经分配的运输任务
            transportTaskMap.remove(transportLineId);
        });
        //没有分配的任务改为人工分配
        transportTaskMap.forEach((key,value)->{
            TaskTransport taskTransport = new TaskTransport();
            taskTransport.setId(value.getId());
            taskTransport.setStatus(3);
            taskTransportFeignClient.updateTaskTransportById(taskTransport);
        });
    }
}
